package com.oba.base.convertor;

import java.io.Serializable;

import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import com.oba.base.dao.BaseDao;
import com.oba.base.interfaces.IBaseBo;
import com.oba.base.util.Util;

public class BoConvertor implements Converter, Serializable {

	private static final long serialVersionUID = 1L;
	static private BaseDao baseDao;

	public Object getAsObject(FacesContext context, UIComponent comp,
			String idStr) {
		ValueExpression ve = comp.getValueExpression("value");
		Class cls = ve.getType(context.getELContext());
		Long id = Long.parseLong(idStr);
		if (id.longValue() == 0)
			return null;
		Object obj;
		if (cls.isArray()) {
			cls = cls.getComponentType();
			obj = getDao().load(cls, id);
		} else {
			IBaseBo curbo = (IBaseBo) ve.getValue(context.getELContext());
			if ((curbo != null && curbo.getId().equals(id))) {
				obj = curbo;
			} else {
				obj = getDao().load(cls, id);
			}
		}
		return obj;
	}

	public String getAsString(FacesContext arg0, UIComponent arg1, Object obj) {
		if (obj == null)
			return null;
		else {
			IBaseBo bo = (IBaseBo) obj;
			return bo.getId().toString();
		}
	}

	public BaseDao getDao() {
		if (baseDao == null) {
			baseDao = (BaseDao) Util.getBean("baseDao");
		}
		return baseDao;
	}

}
